﻿using ApIAuthTest.Basic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace ApIAuthTest.Filter
{
    public class BasicAuthenticationFilterAttribute:AuthorizationFilterAttribute
    {
        public BasicAuthenticationFilterAttribute()
        {
           
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var userIdentity= ParseHeader(actionContext);
            if (userIdentity == null)
            {
                Challenge(actionContext);
                return;
            }
            if (!OnAuthorize(userIdentity.Name, userIdentity.Password, actionContext))
            {
                Challenge(actionContext);
            }
            var pricipal = new GenericPrincipal(userIdentity,null);
            base.OnAuthorization(actionContext);
        }
        
        private BasicAuthenicationIdentity ParseHeader(HttpActionContext actionContext)
        {
            string authparamter = null;
            var authValue = actionContext.Request.Headers.Authorization;
            if (authValue != null && authValue.Scheme == "Basic")
            {
                authparamter = authValue.Parameter;
            }
            if (string.IsNullOrEmpty(authparamter))
            {
                return null;
            }
            authparamter = Encoding.Default.GetString(Convert.FromBase64String(authparamter));
            var authToken = authparamter.Split(':');
            if (authToken.Length < 2)
            {
                return null;
            }
           return new BasicAuthenicationIdentity(authToken[0], authToken[1]);
 
        }
        void Challenge(HttpActionContext actionContext)
        {
            var host = actionContext.Request.RequestUri.DnsSafeHost;
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"",host));
        }
        public virtual bool OnAuthorize(string username, string password, HttpActionContext actionContext)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return false;
            }
            return true;
        }
    }
}